package org.example.common.fastjson;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.annotation.JSONField;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MyFastJSONSerializer implements ObjectSerializer {

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;

        Class<?> clazz = object.getClass();
        List<Field> annotatedFields = getAnnotatedFields(clazz);

        out.write('{');
        boolean isFirst = true;
        for (Field field : annotatedFields) {
            if (!isFirst) {
                out.write(',');
            }
            isFirst = false;

            field.setAccessible(true);
            Object fieldValue = field.get(object);

            JSONField jsonFieldAnnotation = field.getAnnotation(JSONField.class);
            String fieldNameInJson = jsonFieldAnnotation.name();

            serializer.writeFieldName(fieldNameInJson);
            serializer.write(fieldValue);
        }
        out.write('}');
    }

    private List<Field> getAnnotatedFields(Class<?> clazz) {
        List<Field> annotatedFields = new ArrayList<>();
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(JSONField.class)) {
                annotatedFields.add(field);
            }
        }
        return annotatedFields;
    }

}

